/*
 * @Description: 年龄图表
 * @Author: kanglin
 * @Date: 2018-10-30 08:57:53
 * @Copyright: Created by Panxsoft.
 */

 <style lang="less" scoped rel="stylesheet/less" type="text/less" >
    .v-com-gender-chart{
        display: inline-block;
    }
 </style>

<template>
	<div
		ref="gender-chart"
		:style="styles"
		class="v-com-gender-chart"/>
</template>

<script>
import echarts from 'echarts';

const CHARTS_BASIC_CONFIG = {
	// tooltip: {
	// 	trigger: 'item',
	// 	formatter: '<br/>{b}: {c} ({d}%)',
	// },
	title: {
		text: '性别',
		left: '58%',
	},
	color: ['#6D85FF', '#96A6FC', '#B0BCF9'],
	legend: {
		orient: 'vertical',
		x: 'left',
		top: 40,
		data: ['男', '女', '未知'],
	},
	series: [
		{
			// name: '访问来源',
			type: 'pie',
			center: ['64%', '50%'],
			radius: ['55%', '75%'],
			avoidLabelOverlap: false,
			label: {
				normal: {
					show: false,
					position: 'center',
				},
				emphasis: {
					show: true,
					textStyle: {
						color: '#333333',
						fontSize: '32',
						fontWeight: '40',
					},
					formatter: (params) => {
						const { percent } = params;
						return `占比\n${percent}%`;
					},
				},
			},
			labelLine: {
				normal: {
					show: false,
				},
			},
			data: [
				{ value: 335, name: '男' },
				{ value: 310, name: '邮件营销' },
				{ value: 234, name: '联盟广告' },
			],
		},
	],
};

export default {
	name: 'AgeCharts',
	props: {
		styles: {
			type: [Object],
			default() {
				return {
					height: '300px',
					width: '380px',
				};
			},
		},
		genders: {
			type: Array,
			required: true,
		},
	},
	data() {
		return {};
	},
	mounted() {
		// 初始化图表;
		const chart = this.initCharts();
		// 标注化配置
		const config = this.normalizeConfigure(CHARTS_BASIC_CONFIG, this.genders);
		// 设置配置
		chart.setOption(config);
	},
	methods: {
		/**
         * 初始化图表数据
         * @return {Object} EChart 实例
         */
		initCharts() {
			const chartsElement = this.$refs['gender-chart'];
			return echarts.init(chartsElement);
		},

		/**
         * 标注化配置
         * @param {Object} basic_cofig
         * @param {Array} age_groups
         * @return {Object} configure
         */
		normalizeConfigure(basic_cofig, genders) {
			const series_data = [];
			const legend_data = [];
			const gender_map = {
				0: this.$t('common.unknown'),
				1: this.$t('staff.male'),
				2: this.$t('staff.female'),
			};
			genders.forEach((item) => {
				const name = gender_map[item.sex] || this.$t('common.unknown');
				legend_data.push(name);
				series_data.push({ value: item.count, name });
			});
			basic_cofig.legend.data = legend_data;
			basic_cofig.series[0].data = series_data;
			return basic_cofig;
		},
	},
};
</script>
